package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobDto;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobIdDto;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobQuery;
import com.uzai.console.dto.feign.fdSendJob.FdSendJobIdFeignDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsTiktokConversation;
import com.uzai.console.enums.FdGoodsParaEnum;
import com.uzai.console.jsonvo.fd.fdtemplate.FdTemplateData;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdSendJobService;
import com.uzai.console.service.fd.FdSendJobSyncService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.tiktok.TiktokConversationService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.service.wechatprivate.WxContactsSyncService;
import com.uzai.console.vo.fd.fdsendjob.FdSendJobVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 群发任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdSendJobServiceImpl implements FdSendJobService {

    Logger logger = LoggerFactory.getLogger(FdSendJobServiceImpl.class);

    @Autowired
    private FdSendJobMapper fdSendJobMapper;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private WxContactsSyncService wxContactsSyncService;
    @Autowired
    private WxContactsService wxContactsService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private FdDevicePlanGroupMapper fdDevicePlanGroupMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private FdSendJobSyncService fdSendJobSyncService;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TiktokConversationService tiktokConversationService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询群发任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobQuery
     * @return null
     */
    public Page<FdSendJobVo> findFdSendJobList(FdSendJobQuery fdSendJobQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<FdSendJobVo> fdSendJobInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdSendJob> page = new Page<>();
        fdSendJobQuery.convert(page);
        List<FdSendJob> fdSendJobList = fdSendJobMapper.findByList(page, fdSendJobQuery);
        if(fdSendJobList != null){
            for (FdSendJob fdSendJob : fdSendJobList){
                FdSendJobVo fdSendJobInfoVo = new FdSendJobVo();
                BeanUtils.copyProperties(fdSendJob, fdSendJobInfoVo);
                //查询已发送数
                Integer findFinishCount = Tools.getInteger(fdSendJobMapper.findFinishCountByParentId(fdSendJob.getId(), fdSendJob.getMerId()));
                fdSendJobInfoVo.setFinishCount(findFinishCount);

                //查询总数
                Integer totalCount = Tools.getInteger(fdSendJobMapper.findTotalCountByParentId(fdSendJob.getId(), fdSendJob.getMerId()));
                fdSendJobInfoVo.setTotalCount(totalCount);

                //如果完成发送总数大于预计发送总数，则预计发送总数显示为完成发送总数
                if(findFinishCount.intValue() >= totalCount.intValue()){
                    fdSendJobInfoVo.setTotalCount(findFinishCount);
                }

                //修改状态-已完成,必须主任务创建30分钟（1800秒）
                if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.FINISH.getValue().intValue()){
                    if(now - fdSendJob.getCreateTime() > 1800){
                        if(findFinishCount.intValue() >= totalCount.intValue()){
                            fdSendJobInfoVo.setStatus(3);
                            //修改主任务
                            fdSendJob.setStatus(3);
                            fdSendJob.setUpdateTime(now);
                            fdSendJobMapper.updateById(fdSendJob);
                            //修改子任务
                            fdSendJobMapper.updateByParentId(fdSendJob);
                        }
                    }
                }
                fdSendJobInfoVoList.add(fdSendJobInfoVo);

            }
        }
        //返回到页面分页对象
        Page<FdSendJobVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdSendJobInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询群发任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobIdDto
     * @return null
     */
    public FdSendJobVo findFdSendJobInfo(FdSendJobIdDto fdSendJobIdDto){
        //返回到页面的VO对象
        FdSendJobVo fdSendJobInfoVo = new FdSendJobVo();

        if(fdSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobIdDto.getId(), fdSendJobIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(fdSendJob, fdSendJobInfoVo);

        try {
            if(fdSendJob.getData() != null){
                List<FdTemplateData> fdTemplateDataList =  JSONObject.parseArray(fdSendJob.getData(), FdTemplateData.class);
                fdSendJobInfoVo.setFdTemplateDataList(fdTemplateDataList);
            }
        }catch (Exception e){

        }

        return  fdSendJobInfoVo;
    }

    /**
     * 修改群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobDto
     * @return null
     */
    @Transactional
    public void updateFdSendJob(FdSendJobDto fdSendJobDto){
        if(fdSendJobDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob_parent = fdSendJobMapper.selectById(fdSendJobDto.getId(), fdSendJobDto.getMerId());

        if(fdSendJob_parent == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob_parent.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始的任务才能编辑");
        }

        if(StringUtils.isBlank(fdSendJobDto.getName())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入任务名称");
        }

        if(fdSendJobDto.getFdDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        if(fdSendJobDto.getFdTemplateDataList() == null || fdSendJobDto.getFdTemplateDataList().size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入发送内容");
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdSendJobDto.getFdDevicePlanId(), fdSendJobDto.getMerId());
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if(fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置任何群信息");
        }

        //修改主任务
        int now = DateUtil.getNowTime();
        fdSendJob_parent.setName(fdSendJobDto.getName());
        fdSendJob_parent.setSource(0);
        fdSendJob_parent.setFdDevicePlanId(fdSendJobDto.getFdDevicePlanId());
        fdSendJob_parent.setStatus(0); //未开始
        fdSendJob_parent.setData(JSONObject.toJSONString(fdSendJobDto.getFdTemplateDataList()));
        fdSendJob_parent.setTotalCount(0);
        fdSendJob_parent.setFinishCount(0);
        fdSendJob_parent.setFinishCountSnapshot(0);
        fdSendJob_parent.setBeginTime(fdSendJobDto.getBeginTime());
        fdSendJob_parent.setExptime(fdSendJobDto.getBeginTime() + 7 * 24 * 3600);
        fdSendJob_parent.setCreateTime(now);
        fdSendJob_parent.setUpdateTime(now);
        fdSendJob_parent.setBeginTime(fdSendJobDto.getBeginTime());
        fdSendJob_parent.setSendStartTime(fdSendJob_parent.getBeginTime() + 60);//在开始时间之后60秒发送
        fdSendJobMapper.updateById(fdSendJob_parent);

        //删除子任务
        fdSendJobMapper.deleteByParentId(fdSendJob_parent.getId(), fdSendJob_parent.getMerId());

        //删除群发任务ES数据
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.setQuery(new TermQueryBuilder("parentJobId", fdSendJob_parent.getId()));
        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJob_parent.getMerId());
        elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_group_send_msg, deleteByQueryRequest);

        //封装子任务
        //封装所有群(子任务)
        List<FdSendJob> fdSendJobList_sub = new ArrayList<>();
        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            FdSendJob fdSendJob_sub = new FdSendJob();
            fdSendJob_sub.setId(IdWorker.getId());
            fdSendJob_sub.setParentId(fdSendJob_parent.getId());
            fdSendJob_sub.setMerId(fdSendJob_parent.getMerId());
            fdSendJob_sub.setName(fdSendJob_parent.getName());
            fdSendJob_sub.setSource(fdSendJob_parent.getSource());
            fdSendJob_sub.setFdDevicePlanId(fdSendJob_parent.getFdDevicePlanId());
            fdSendJob_sub.setStatus(0); //未开始
            fdSendJob_sub.setData(fdSendJob_parent.getData());
            fdSendJob_sub.setTotalCount(0);
            fdSendJob_sub.setFinishCount(0);
            fdSendJob_sub.setFinishCountSnapshot(0);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setExptime(fdSendJob_parent.getBeginTime() + 15 * 24 * 3600);
            fdSendJob_sub.setCreateTime(now);
            fdSendJob_sub.setUpdateTime(now);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setSendStartTime(fdSendJob_sub.getBeginTime() + 60);//在开始时间之后60秒发送
            //群发机器人消息
            fdSendJob_sub.setDeviceType(fdDevicePlanGroup.getDeviceType());
            fdSendJob_sub.setGroupId(fdDevicePlanGroup.getGroupId());
            fdSendJob_sub.setNick(fdDevicePlanGroup.getNick());
            fdSendJob_sub.setDeviceUniqueId(fdDevicePlanGroup.getDeviceUniqueId());
            fdSendJob_sub.setDeviceId(fdDevicePlanGroup.getDeviceId());
            fdSendJob_sub.setWxid(fdDevicePlanGroup.getWxid());
            fdSendJob_sub.setGroupSendDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
            fdSendJobList_sub.add(fdSendJob_sub);
        }

        //重新添加发单发送任务
        fdSendJobSyncService.addFdSendJobTaskSync(fdSendJobDto, fdDevicePlan,  fdDevicePlanGroupList, fdSendJobList_sub);
    }

    /**
     * 开始群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobIdDto
     * @return null
     */
    @Transactional
    public void startFdSendJob(FdSendJobIdDto fdSendJobIdDto){
        if(fdSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobIdDto.getId(), fdSendJobIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue() && fdSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能开启");
        }

        Integer now = DateUtil.getNowTime();
        if(fdSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
            fdSendJob.setBeginTime(now);
            fdSendJob.setSendStartTime(fdSendJob.getBeginTime() + 60);//在开始时间之后60秒发送
        }else{//暂停中的任务延迟5分钟发送
            fdSendJob.setBeginTime(now+60*5); //延迟5分钟
            fdSendJob.setSendStartTime(fdSendJob.getBeginTime() + 60);//在开始时间之后60秒发送
        }
        fdSendJob.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJobMapper.updateById(fdSendJob);

        //查询未开始的子任务，修改状态为开始
        FdSendJobQuery fdSendJobQuery = new FdSendJobQuery();
        fdSendJobQuery.setMerId(fdSendJobIdDto.getMerId());
        fdSendJobQuery.setParentId(fdSendJob.getId());
        List<FdSendJob> fdSendJobQueryList =  fdSendJobMapper.findByList(fdSendJobQuery);
        if(fdSendJobQueryList != null){
            for (FdSendJob fdSendJobSon : fdSendJobQueryList){
                //未开始或者暂停的子任务-将状态修改成进行中
                if(fdSendJobSon.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()
                        || fdSendJobSon.getStatus().intValue() == GroupSendStatusEnum.PAUSE.getValue().intValue()
                ){

                    if(fdSendJobSon.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
                        fdSendJobSon.setBeginTime(now);
                        fdSendJobSon.setSendStartTime(fdSendJobSon.getBeginTime() + 60);//在开始时间之后60秒发送
                    }else{//暂停中的任务延迟5分钟发送
                        fdSendJobSon.setBeginTime(now+60*5); //延迟5分钟
                        fdSendJobSon.setSendStartTime(fdSendJobSon.getBeginTime() + 60);//在开始时间之后60秒发送
                    }

                    fdSendJobSon.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());
                    fdSendJobSon.setUpdateTime(now);
                    fdSendJobSon.setFinishCountSnapshot(fdSendJobSon.getFinishCount());
                    //从ES中获取该子任务的已发送数
                    FdSendJobIdFeignDto fdSendJobIdFeignDto = new FdSendJobIdFeignDto();
                    fdSendJobIdFeignDto.setId(fdSendJobSon.getId());
                    UzaiRespVo<Integer> uzaiRespVo = uzaiBroadcastFeignService.fdSendFinishCount(fdSendJobIdFeignDto);
                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                        if(Tools.getInteger(uzaiRespVo.getData()).intValue() != 0){
                            fdSendJobSon.setFinishCountSnapshot(uzaiRespVo.getData());
                        }
                    }
                    fdSendJobMapper.updateByIdSelective(fdSendJobSon);
                }
            }
        }
    }

    /**
     * 暂停群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobIdDto
     * @return null
     */
    @Transactional
    public void pauseFdSendJob(FdSendJobIdDto fdSendJobIdDto){
        if(fdSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobIdDto.getId(), fdSendJobIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能暂停");
        }

        Integer now = DateUtil.getNowTime();
        fdSendJob.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJobMapper.updateById(fdSendJob);

        //批量修改子任务
        //查询未开始的子任务，修改状态为开始
        FdSendJobQuery fdSendJobQuery = new FdSendJobQuery();
        fdSendJobQuery.setMerId(fdSendJobIdDto.getMerId());
        fdSendJobQuery.setParentId(fdSendJob.getId());
        List<FdSendJob> fdSendJobQueryList =  fdSendJobMapper.findByList(fdSendJobQuery);
        if(fdSendJobQueryList != null) {
            for (FdSendJob fdSendJobSon : fdSendJobQueryList) {
                //进行中的任务-将状态修改成暂停
                if(fdSendJobSon.getStatus().intValue() == GroupSendStatusEnum.RUNNING.getValue().intValue()){
                    fdSendJobSon.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
                    fdSendJobSon.setUpdateTime(now);
                    fdSendJobMapper.updateByIdSelective(fdSendJobSon);
                }
            }
        }

    }

    /**
     * 结束群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobIdDto
     * @return null
     */
    @Transactional
    public void finishFdSendJob(FdSendJobIdDto fdSendJobIdDto){
        if(fdSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobIdDto.getId(), fdSendJobIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()
                && fdSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中或暂停中的任务才能结束");
        }

        Integer now = DateUtil.getNowTime();
        fdSendJob.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJobMapper.updateById(fdSendJob);

        //批量修改子任务
        FdSendJobQuery fdSendJobQuery = new FdSendJobQuery();
        fdSendJobQuery.setMerId(fdSendJobIdDto.getMerId());
        fdSendJobQuery.setParentId(fdSendJob.getId());
        List<FdSendJob> fdSendJobQueryList =  fdSendJobMapper.findByList(fdSendJobQuery);
        if(fdSendJobQueryList != null) {
            for (FdSendJob fdSendJobSon : fdSendJobQueryList) {
                fdSendJobSon.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
                fdSendJobSon.setUpdateTime(now);
                fdSendJobMapper.updateByIdSelective(fdSendJobSon);
            }
        }
    }

    /**
     * 删除群发任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobIdDto
     * @return null
     */
    @Transactional
    public void deleteFdSendJob(FdSendJobIdDto fdSendJobIdDto){

//        if(true){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前版本不支持删除群发任务功能");
//        }

        if(fdSendJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobIdDto.getId(), fdSendJobIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能删除未开始的任务");
        }

        //删除主任务
        fdSendJobMapper.deleteById(fdSendJob.getId(), fdSendJobIdDto.getMerId());

        //删除子任务
        fdSendJobMapper.deleteByParentId(fdSendJob.getId(), fdSendJobIdDto.getMerId());

        //删除群发任务ES数据
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.setQuery(new TermQueryBuilder("parentJobId", fdSendJob.getId()));

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJobIdDto.getMerId());
        elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_group_send_msg, deleteByQueryRequest);
    }

    /**
     * 手动发送发单任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobDto
     * @return null
     */
    @Transactional
    public void addFdSendJob(FdSendJobDto fdSendJobDto){

        if(StringUtils.isBlank(fdSendJobDto.getName())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入任务名称");
        }

        if(fdSendJobDto.getFdDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdSendJobDto.getFdDevicePlanId(), fdSendJobDto.getMerId());
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if(fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置任何群信息");
        }

        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
            if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信

                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), fdDevicePlanGroup.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if(wxgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxgroup_manageplan_id, fdSendJobDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdSendJobDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), fdDevicePlanGroup.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if(wxworkgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxworkgroup_manageplan_id, fdSendJobDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdSendJobDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                JSONObject jsonObject = null;

                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.TIKTOK.getKey())){//抖音设备
                String esName = EsIndexName.UZAI_TIKTOK_CONVERSATION;
                String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, fdSendJobDto.getMerId());
                Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, fdDevicePlanGroup.getGroupId(), null);
                EsTiktokConversation esTiktokConversation  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsTiktokConversation.class);
                if(esTiktokConversation == null || Tools.getLong(esTiktokConversation.getManagePlanId()) == 0 ){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群会话id为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById(esTiktokConversation.getManagePlanId(), fdSendJobDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdSendJobDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }
        }

        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = fdSendJobDto.getFdTemplateDataList();
        if(fdTemplateDataList == null || fdTemplateDataList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入发送内容");
        }

        //判断必须有文本框，如果文本框内容是否包含淘口令，如果包含，则判断此文本第一个字必须是数字
        boolean goodsFlag = false; //是否包含文本
        boolean pwdFlag = false;   //是否包含淘口令
        boolean shortLinkFlag = false; //是否包含短链接
        for (FdTemplateData fdTemplateData : fdTemplateDataList) {
            if(Tools.getInteger(fdTemplateData.getMsgType().intValue()) == 0){ //文本

                String content = fdTemplateData.getContent();

                if(StringUtils.isBlank(content)){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入文本内容");
                }
                //包含文本
                goodsFlag = true;
                //包含淘口令
                //查询淘口令变量[淘口令+ID]
                String regex_pwd = FdGoodsParaEnum.PWD.getRegex();
                List<String> pwdList = Tools.findStrMatchListByRegex(content, regex_pwd);
                if(pwdList != null && pwdList.size() > 0){
                    pwdFlag = true;
                    //判断此文本框是否以数字开头（淘口令文本框第一个字必须是数字）
                    if(!Character.isDigit(content.charAt(0))){
                        //throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "包含淘口令的文本框内容第一个字符必须是数字");
                    }
                }
                //包含短链接
                //查询短链接变量[短链接+ID]
                String regex_shortLink = FdGoodsParaEnum.SHORTLINK.getRegex();
                List<String> shortLinkList = Tools.findStrMatchListByRegex(content, regex_shortLink);
                if(shortLinkList != null && shortLinkList.size() > 0){
                    shortLinkFlag = true;
                }
            }
        }

        if(!goodsFlag){
            //throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "至少含有一个文本消息");
        }

        if(!pwdFlag && !shortLinkFlag){
            //throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "至少包含一个淘口令或短链接");
        }

        //主任务
        int now = DateUtil.getNowTime();
        FdSendJob fdSendJob_parent = new FdSendJob();
        fdSendJob_parent.setId(IdWorker.getId());
        fdSendJob_parent.setParentId(0L);
        fdSendJob_parent.setMerId(fdSendJobDto.getMerId());
        fdSendJob_parent.setName(fdSendJobDto.getName());
        fdSendJob_parent.setSource(0);
        fdSendJob_parent.setFdDevicePlanId(fdSendJobDto.getFdDevicePlanId());
        fdSendJob_parent.setStatus(0); //未开始
        fdSendJob_parent.setData(JSONObject.toJSONString(fdSendJobDto.getFdTemplateDataList()));
        fdSendJob_parent.setTotalCount(0);
        fdSendJob_parent.setFinishCount(0);
        fdSendJob_parent.setFinishCountSnapshot(0);
        fdSendJob_parent.setBeginTime(fdSendJobDto.getBeginTime());
        fdSendJob_parent.setExptime(fdSendJobDto.getBeginTime() + 7 * 24 * 3600);
        fdSendJob_parent.setCreateTime(now);
        fdSendJob_parent.setUpdateTime(now);
        fdSendJob_parent.setBeginTime(fdSendJobDto.getBeginTime());
        fdSendJob_parent.setSendStartTime(fdSendJobDto.getBeginTime() + 60); //在开始时间之后60秒发送
        fdSendJobMapper.insertSelective(fdSendJob_parent);

        //封装子任务
        //封装所有群(子任务)
        List<FdSendJob> fdSendJobList_sub = new ArrayList<>();
        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            FdSendJob fdSendJob_sub = new FdSendJob();
            fdSendJob_sub.setId(IdWorker.getId());
            fdSendJob_sub.setParentId(fdSendJob_parent.getId());
            fdSendJob_sub.setMerId(fdSendJob_parent.getMerId());
            fdSendJob_sub.setName(fdSendJob_parent.getName());
            fdSendJob_sub.setSource(fdSendJob_parent.getSource());
            fdSendJob_sub.setFdDevicePlanId(fdSendJob_parent.getFdDevicePlanId());
            fdSendJob_sub.setStatus(0); //未开始
            fdSendJob_sub.setData(fdSendJob_parent.getData());
            fdSendJob_sub.setTotalCount(0);
            fdSendJob_sub.setFinishCount(0);
            fdSendJob_sub.setFinishCountSnapshot(0);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setExptime(fdSendJob_parent.getBeginTime() + 15 * 24 * 3600);
            fdSendJob_sub.setCreateTime(now);
            fdSendJob_sub.setUpdateTime(now);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setSendStartTime(fdSendJob_parent.getSendStartTime());
            //群发机器人消息
            fdSendJob_sub.setDeviceType(fdDevicePlanGroup.getDeviceType());
            fdSendJob_sub.setGroupId(fdDevicePlanGroup.getGroupId());
            fdSendJob_sub.setNick(fdDevicePlanGroup.getNick());
            fdSendJob_sub.setDeviceUniqueId(fdDevicePlanGroup.getDeviceUniqueId());
            fdSendJob_sub.setDeviceId(fdDevicePlanGroup.getDeviceId());
            fdSendJob_sub.setWxid(fdDevicePlanGroup.getWxid());
            fdSendJob_sub.setGroupSendDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
            fdSendJobList_sub.add(fdSendJob_sub);
        }

        fdSendJobSyncService.addFdSendJobTaskSync(fdSendJobDto, fdDevicePlan,  fdDevicePlanGroupList, fdSendJobList_sub);

    }


}
